Vue.component('category-management', {
  data() {
    return {
      categories: [],
      categoryTree: [],
      loading: false,
      searchForm: {
        name: '',
        parent_id: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        name: '',
        description: '',
        parent_id: null
      },
      formRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      parentCategories: [],
      expandedKeys: []
    };
  },
  methods: {
    async loadCategories() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize
        };
        
        // 处理搜索参数
        if (this.searchForm.name) {
          params.name = this.searchForm.name;
        }
        if (this.searchForm.parent_id) {
          params.parent_id = this.searchForm.parent_id;
        }
        
        const response = await categoryAPI.getCategories(params);
        this.categories = response.data.categories;
        this.total = response.data.pagination.total;
      } catch (error) {
        console.error('获取分类列表失败:', error);
        this.$message.error(error.message || '获取分类列表失败');
      } finally {
        this.loading = false;
      }
    },
    async loadCategoryTree() {
      try {
        const response = await categoryAPI.getCategoryTree();
        this.categoryTree = response.data;
        this.parentCategories = this.buildParentOptions(response.data);
      } catch (error) {
        console.error('获取分类树失败:', error);
      }
    },
    buildParentOptions(tree, level = 0) {
      let options = [];
      tree.forEach(item => {
        options.push({
          value: item.id,
          label: '　'.repeat(level) + item.name,
          level: level
        });
        if (item.children && item.children.length > 0) {
          options = options.concat(this.buildParentOptions(item.children, level + 1));
        }
      });
      return options;
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadCategories();
    },
    handleReset() {
      this.searchForm = {
        name: '',
        parent_id: ''
      };
      this.currentPage = 1;
      this.loadCategories();
    },
    handleAdd() {
      this.dialogTitle = '添加分类';
      this.formData = {
        id: null,
        name: '',
        description: '',
        parent_id: null
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑分类';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate();
        
        // 处理表单数据
        const submitData = {
          name: this.formData.name,
          description: this.formData.description || '',
          parent_id: this.formData.parent_id || null
        };
        
        console.log('提交的数据:', submitData);
        
        if (this.formData.id) {
          // 编辑分类
          const response = await categoryAPI.updateCategory(this.formData.id, submitData);
          console.log('更新分类响应:', response);
          this.$message.success('分类更新成功');
        } else {
          // 创建分类
          const response = await categoryAPI.createCategory(submitData);
          console.log('创建分类响应:', response);
          this.$message.success('分类创建成功');
        }
        
        this.dialogVisible = false;
        this.loadCategories();
        this.loadCategoryTree();
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(error.message || '操作失败');
      }
    },
    handleDelete(row) {
      this.$confirm('确定要删除该分类吗？删除后该分类下的所有子分类和商品也将被删除！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await categoryAPI.deleteCategory(row.id);
          this.$message.success('删除成功');
          this.loadCategories();
          this.loadCategoryTree();
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error(error.message || '删除失败');
        }
      });
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadCategories();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadCategories();
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString();
    },
    getParentName(parentId) {
      if (!parentId) return '顶级分类';
      const parent = this.parentCategories.find(p => p.value === parentId);
      return parent ? parent.label.trim() : '未知分类';
    },
    // 树形表格相关方法
    loadTreeData() {
      // 这里可以加载树形数据用于树形表格显示
      this.loadCategoryTree();
    },
    handleTreeExpand(row, expanded) {
      // 处理树形表格展开/收起
    }
  },
  async mounted() {
    await Promise.all([
      this.loadCategories(),
      this.loadCategoryTree()
    ]);
  },
  template: `
    <div class="category-management">
      <el-card>
        <div slot="header">
          <span>分类管理</span>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;" size="small">
            添加分类
          </el-button>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline style="margin-bottom: 15px;">
          <el-form-item label="分类名称">
            <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable size="small" style="width: 180px;"></el-input>
          </el-form-item>
          <el-form-item label="父分类">
            <el-select v-model="searchForm.parent_id" placeholder="请选择父分类" clearable size="small" style="width: 180px;">
              <el-option
                v-for="item in parentCategories"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 分类表格 -->
        <el-table :data="categories" v-loading="loading" border size="small" :cell-style="{padding: '8px 0'}">
          <el-table-column prop="name" label="分类名称" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="parent_name" label="父分类" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.parent_name || '顶级分类' }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="120">
            <template slot-scope="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" style="color: #f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          size="small"
          style="margin-top: 15px; text-align: right;">
        </el-pagination>
      </el-card>
      
      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form :model="formData" :rules="formRules" ref="form" label-width="100px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item label="父分类">
            <el-select v-model="formData.parent_id" placeholder="请选择父分类（不选则为顶级分类）" style="width: 100%;" clearable>
              <el-option
                v-for="item in parentCategories"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="formData.description" placeholder="请输入分类描述" :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </div>
  `
});
